<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->

      <PageTools>
        <template #left>总记录数:20条</template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
            >导入excel</el-button
          >
          <el-button type="danger" size="small" @click="hExportExcel"
            >导出excel</el-button
          >
          <el-button type="primary" size="small" @click="showDialog = true"
            >新增员</el-button
          >
        </template>
      </PageTools>

      <el-card style="margin-top: 10px">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template v-slot="scope">{{
              formatType(scope.row.formOfEmployment)
            }}</template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
                >查看</el-button
              >
              <el-button type="text" size="small" @click="hAssign(scope.row.id)"
                >分配角色</el-button
              >
              <el-button type="text" size="small" @click="hDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
            :current-page.sync="page"
            :total="total"
            :page-size="size"
            :page-sizes="[3, 5, 10, 20]"
            layout="total,sizes,prev,pager,next"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addor-edit
          v-if="showDialog"
          @close="showDialog = false"
          @success="hSuccess"
        />
      </el-dialog>
      <el-dialog :visible.sync="showDialogRole">
        <AssignRole v-if="showDialogRole" :curId="curId" @success="hSuccessRoles" @close="showDialogRole = false"/>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import addorEdit from "./empDialog.vue";
import AssignRole from "./assignRole.vue";
import EmployeENUM from "@/constant/employees";
const EMPLOYTYPE = EmployeENUM.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value;
  return acc;
}, {});
console.log(EmployeENUM.hireType, EMPLOYTYPE);
import { getEmployees, delEmployees } from "@/api/employees.js";
export default {
  data() {
    return {
      showDialog: false,
      showDialogRole: false,
      list: [],
      size: 15, //每页几条
      page: 1, //当前页码
      total: 0, //总共数据条数
      curId: "", //当前员工的Id
    };
  },
  components: { "addor-edit": addorEdit, AssignRole },
  created() {
    this.loadEmployees();
  },
  methods: {
    hSuccessRoles() {
      // 子组件保存角色成功;
      this.showDialogRole = false;
      // 更新页面
      this.loadEmployees()
    },
    hAssign(id) {
      this.showDialogRole = true;
      // 保存id
      this.curId = id;
    },
    // 处理函数
    transformData(list) {
      const map = {
        // 中英文装换
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址",
      };
      console.log(list);
      let header = [];
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = [];
      // 开始代码
      // 找到一个元素
      const one = list[0];
      if (!one) {
        return { header, data };
      }
      header = Object.keys(one).map((key) => {
        return map[key];
      });

      // data把list中每一个对象转成 对应的value数组
      data = list.map((obj) => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj["formOfEmployment"]; // 1, 2
        obj["formOfEmployment"] = EMPLOYTYPE[key]; // {1:'正式', '2':'非正式' }

        return Object.values(obj);
      });

      return { header, data };
    },
    // 点击导出excle文件
    hExportExcel() {
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 发ajax请求，获取数据
        const res = await getEmployees({ page: this.page, size: this.size });
        const list = res.data.rows;
        console.log("从后端获取的数据", list);

        const { header, data } = this.transformData(list);
        // excel表示导入的模块对象
        console.log(header, data);
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: "员工信息表", // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: "xlsx", // 生成的文件类型
        });
      });
    },
    // 添加新员工成功了
    hSuccess() {
      this.showDialog = false;

      // 跳转到最后一页去看数据
      this.total++;
      this.page = Math.ceil(this.total / this.size);
      this.loadEmployees();
    },
    // 删除
    async doDel(id) {
      try {
        const res = await delEmployees(id);
        console.log("delEmployee", res);

        // 重发请求
        this.loadEmployees();
      } catch (err) {
        console.log("delEmployees", err);
      }
    },

    hDel(id) {
      console.log(id);
      this.$confirm("确认删除吗？")
        .then(() => {
          this.doDel(id);
        })
        .catch(() => {});
    },
    // 用户点击了页码
    hCurrentChange(curPage) {
      // 更新页码
      this.page = curPage;
      // 重发请求
      this.loadEmployees();
    },
    // 用户切换了,每页几条
    hSizeChange(curSize) {
      // 更新每一页几条,统一让他求第一页
      this.page = 1;
      this.size = curSize;
      // 重发请求
      this.loadEmployees();
    },
    formatType(typeId) {
      // const item = EmployeENUM.hireType.find(item => item.id === typeId)
      // if (item) {
      //   return item.value
      // } else {
      //   return '未知'
      // }
      return EMPLOYTYPE[typeId] || "未知";
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size });
        console.log(res);
        this.list = res.data.rows;
        this.total = res.data.total;
      } catch (err) {
        console.log(err);
        this.$message.error("加载员工数据失败");
      }
    },
  },
};
</script>